import urllib2
import urllib
import re

class DelicApi :
	add_new_bookmark_uri = "https://api.del.icio.us/v1/posts/add?"
	
	def __init__(self, del_user, del_pass):
		self.makeAuthen(del_user, del_pass)

	def makeAuthen(self, del_user, del_pass):
		pass_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
		pass_mgr.add_password(None, "https://api.del.icio.us/" , del_user, del_pass)

		auth_handler = urllib2.HTTPBasicAuthHandler(pass_mgr)
		opener = urllib2.build_opener(auth_handler)
		urllib2.install_opener(opener)

	def addNewBookmark(self,url,description,tags,shared="yes",replace="yes"):
		args = "url=%s&description=%s&tags=%s&shared=%s&replace=%s" % (url,description,tags,shared,replace)
		new_args = args.replace(" ","+")
		result = urllib2.urlopen( self.add_new_bookmark_uri + new_args).read()

		pattern = '''<result code="(.+?)" />'''
		code = re.compile(pattern).findall(result)[0]
		
		if not code == "done" :
			return False 
		return True
	
	def setAccount(del_user, del_pass):
		self.makeAuthen(del_user, del_pass)

	def test(self):
		xml = urllib2.urlopen("https://api.del.icio.us/v1/posts/recent").read()
		print xml


if __name__ == "__main__" :
	del_user = "wearetherock"
	del_pass = "fs234!$"
	
	d = DelicApi(del_user,del_pass)
	d.addNewBookmark("http://www.google.com", "test del api", "google test pyhon 1234")


